//
//  UUHomePageVC.m
//  UUCharterSupplier
//
//  Created by ZhangAo on 14/01/2018.
//  Copyright © 2018 UUCharter. All rights reserved.
//

#import "UUHomePageVC.h"
#import "UUOrderManager.h"
#import "UUUserManager.h"
#import "UUSupplierManager.h"
#import "UUResourceManager.h"
#import "UUOrderCell.h"
#import "UUOrderStateListVC.h"
#import "UUOrderDetailVC.h"
#import "UUOrderAssignVC.h"
#import "UUSupplierReviewStatusTipsView.h"
#import "UUIntentOrderManager.h"
#import "UUIntentOrderListVC.h"

@interface UUHomePageSectionHeader : UITableViewHeaderFooterView

@property (nonatomic, strong) UILabel *titleLabel;

@end

@implementation UUHomePageSectionHeader

- (instancetype)initWithReuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithReuseIdentifier:reuseIdentifier];
    if (self) {
        self.titleLabel = [UILabel new];
        self.titleLabel.font = [UIFont systemFontOfSize:14];
        self.titleLabel.textColor = COMMON_TEXT_RED_COLOR;
        [self.contentView addSubview:self.titleLabel];
        
        [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(15);
            make.right.mas_equalTo(-15);
            make.centerY.mas_equalTo(0);
        }];
    }
    return self;
}

@end
////////////////////////////////////////////////////////////////////////////////

@interface UUHomePageMoreCell : UUBaseTableViewCell

@property (nonatomic, weak) IBOutlet UILabel *moreLabel;

@end

@implementation UUHomePageMoreCell

@end

////////////////////////////////////////////////////////////////////////////////

@interface UUHomePageVC () <UITableViewDelegate, UITableViewDataSource, UUOrderManagerObserver, UUUserManagerObserver>

@property (nonatomic, strong) DKOffsetTitleView *titleView;
@property (nonatomic, weak) IBOutlet UITableView *tableView;

@property (nonatomic, weak) IBOutlet UIView *headerView;
@property (nonatomic, weak) IBOutlet UIView *headerBakcgroundView;
@property (nonatomic, weak) IBOutlet UILabel *priceLabel;
@property (nonatomic, weak) IBOutlet UILabel *subtitleLabel;

@property (nonatomic, weak) IBOutlet UILabel *enterance1Label;
@property (nonatomic, weak) IBOutlet UILabel *enterance2Label;
@property (nonatomic, weak) IBOutlet UILabel *enterance3Label;
@property (nonatomic, weak) IBOutlet UILabel *enterance4Label;

@property (nonatomic, weak) IBOutlet UILabel *enteranceNumber1Label;
@property (nonatomic, weak) IBOutlet UILabel *enteranceNumber2Label;
@property (nonatomic, weak) IBOutlet UILabel *enteranceNumber3Label;
@property (nonatomic, weak) IBOutlet UILabel *enteranceNumber4Label;

@property (nonatomic, copy) NSArray<id> *ordersForWaitingForConfirm;
@property (nonatomic, copy) NSArray<id> *ordersForWaitingForService;
@property (nonatomic, copy) NSArray<id> *ordersForWaitingForAssign;

@property (nonatomic, strong) UUSupplierReviewStatusTipsView *reviewStatusTipsView;
@property (nonatomic, strong) UIImageView *emptyImageView;

@end

@implementation UUHomePageVC

+ (BOOL)enableTranslucentNavigationBar {
    return YES;
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"首页";
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
 
    self.headerBakcgroundView.backgroundColor = COMMON_TRANSLUCENT_NAVIGATIONBAR_COLOR;
    
    [self.translucentNavigationBar setBackgroundImage:[UIImage imageFromColor:COMMON_TRANSLUCENT_NAVIGATIONBAR_COLOR]
                                       forBarPosition:UIBarPositionTopAttached
                                           barMetrics:UIBarMetricsDefault];
    self.translucentNavigationBar.translucent = NO;
    
    DKStickyHeaderView *stickyHeaderView = [[DKStickyHeaderView alloc] initWithMinHeight:0];
    stickyHeaderView.backgroundColor = COMMON_TRANSLUCENT_NAVIGATIONBAR_COLOR;
    [self.tableView addSubview:stickyHeaderView];
    
    self.titleView = [[DKOffsetTitleView alloc] initWithTitle:@"首页"];
    self.titleView.yOffset = 90;
    [self setupBarTitleView:self.titleView];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"UUOrderCell" bundle:nil] forCellReuseIdentifier:@"Cell"];
    [self.tableView registerClass:[UUHomePageSectionHeader class] forHeaderFooterViewReuseIdentifier:@"Header"];

    self.subtitleLabel.text = @"总收入";
    self.subtitleLabel.textColor = RGB_COLOR(161, 157, 175);
    
    self.enterance1Label.textColor = RGB_COLOR(80, 80, 80);
    self.enterance2Label.textColor = self.enterance1Label.textColor;
    self.enterance3Label.textColor = self.enterance1Label.textColor;
    self.enterance4Label.textColor = self.enterance1Label.textColor;
    
    [self updateLabel:self.enteranceNumber4Label withNumber:0];
    
    [self updateOrders];
    
    [GetOrderManager() addObserver:self];
    [GetUserManager() addObserver:self];
    
    self.reviewStatusTipsView = [[UUSupplierReviewStatusTipsView alloc] initWithContainerViewController:self];
    [self.reviewStatusTipsView update];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self updateTotalIncome];
    [self updateIntentOrderCount];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)updateOrders {
    self.ordersForWaitingForService = [GetOrderManager() fetchOrdersForStatus:UUOrderStatusWaitingForService];
    self.ordersForWaitingForConfirm = [GetOrderManager() fetchOrdersForStatus:UUOrderStatusWaitingForConfirm];
    self.ordersForWaitingForAssign = [GetOrderManager() fetchOrdersForStatus:UUOrderStatusWaitingForAssign];
    
    [self updateLabel:self.enteranceNumber1Label withNumber:self.ordersForWaitingForService.count];
    [self updateLabel:self.enteranceNumber2Label withNumber:self.ordersForWaitingForConfirm.count];
    [self updateLabel:self.enteranceNumber3Label withNumber:self.ordersForWaitingForAssign.count];
    
    if (self.ordersForWaitingForService.count + self.ordersForWaitingForConfirm.count + self.ordersForWaitingForAssign.count == 0) {
        if (self.emptyImageView == nil) {
            self.emptyImageView = [[UIImageView alloc] initWithImage:GetResourceManager().emptyDataImage];
            [self.tableView addSubview:self.emptyImageView];
            [self.emptyImageView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.mas_equalTo(0);
                make.top.mas_equalTo(340);
            }];
        }
        
        self.emptyImageView.hidden = NO;
    } else {
        self.emptyImageView.hidden = YES;
    }
    
    [self.tableView reloadData];
}

- (void)updateTotalIncome {
    WEAK_SELF();
    [GetSupplierManager() asyncFetchTotalIncomeWithCompleteBlock:^(NSNumber *totalIncome, NSError *error) {
        if (error == nil) {
            NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:[totalIncome toCurrencyWithoutCurrencySymbol]
                                                                                               attributes:@{
                                                                                                            NSForegroundColorAttributeName : [UIColor whiteColor],
                                                                                                            NSFontAttributeName : [UIFont systemFontOfSize:30]
                                                                                                            }];
            [attributedText appendAttributedString:[[NSAttributedString alloc] initWithString:@"元"
                                                                                   attributes:@{
                                                                                                NSForegroundColorAttributeName : [UIColor whiteColor],
                                                                                                NSFontAttributeName : [UIFont systemFontOfSize:12]
                                                                                                }]];
            weakSelf.priceLabel.attributedText = attributedText;
        }
    }];
}

- (void)updateIntentOrderCount {
    WEAK_SELF();
    [GetIntentOrderManager() asyncFetchIntentCountWithCompleteBlock:^(NSInteger count, NSError *error) {
        if (error == nil) {
            [weakSelf updateLabel:weakSelf.enteranceNumber4Label withNumber:count];
        }
    }];
}

- (void)updateLabel:(UILabel *)label withNumber:(NSInteger)number {
    label.text = INT_TO_STRING(number);
    
    if (number == 0) {
        label.textColor = RGB_COLOR(216, 216, 216);
    } else {
        label.textColor = COMMON_TEXT_ORANGE_COLOR;
    }
}

- (IBAction)headerButtonDidTap:(UIView *)sender {
    NSInteger tag = sender.tag;
    if (tag == 4) {
        [self.navigationController pushViewController:[UUIntentOrderListVC instanceOfAppropriate] animated:YES];
    } else {
        UUOrderStatus status = UUOrderStatusNone;
        switch (sender.tag) {
            case 1:
                status = UUOrderStatusWaitingForService;
                break;
            case 2:
                status = UUOrderStatusWaitingForConfirm;
                break;
            case 3:
                status = UUOrderStatusWaitingForAssign;
                break;
            default:
                DKAssert(0);
                break;
        }
        
        [self switchToOrderStatus:status];
    }
}

- (void)switchToOrderStatus:(UUOrderStatus)status {
    UUOrderStateListVC *orderListVC = [UUOrderStateListVC orderStateListVCWithStatus:status];
    [self.navigationController pushViewController:orderListVC animated:YES];
}

- (id)orderIdForIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return self.ordersForWaitingForConfirm[indexPath.row];
    } else {
        if (indexPath.row < self.ordersForWaitingForAssign.count) {
            return self.ordersForWaitingForAssign[indexPath.row];
        } else {
            return self.ordersForWaitingForService[indexPath.row - self.ordersForWaitingForAssign.count];
        }
    }
}

#pragma mark - UITableViewDelegate, UITableViewDataSource methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return MIN(self.ordersForWaitingForConfirm.count, 4);
    } else {
        return MIN(self.ordersForWaitingForAssign.count + self.ordersForWaitingForService.count, 4);
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 3) {
        return 45;
    } else {
        return [UUOrderCell preferredHeight];
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 0 && self.ordersForWaitingForConfirm.count == 0) {
        return nil;
    } else if (self.ordersForWaitingForAssign.count + self.ordersForWaitingForService.count == 0) {
        return nil;
    }
    
    UUHomePageSectionHeader *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"Header"];
    if (section == 0) {
        header.titleLabel.text = @"待确认";
    } else {
        header.titleLabel.text = @"待发车";
    }
    return header;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 40;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UUBaseTableViewCell *_cell;
    if (indexPath.row == 3) {
        UUHomePageMoreCell *cell = [tableView dequeueReusableCellWithIdentifier:@"More" forIndexPath:indexPath];
        cell.moreLabel.font = [GetResourceManager() iconFontWithSize:12];
        cell.moreLabel.textColor = COMMON_TEXT_LIGHT_COLOR;
        cell.moreLabel.text = GetResourceManager().seeMoreIconText;
        
        _cell = cell;
    } else {
        UUOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
        
        NSNumber *orderId = [self orderIdForIndexPath:indexPath];
        
        UUOrderModel *model = [GetOrderManager() fetchOrderWithOrderId:orderId];
        [cell setupWithModel:model];
        
        WEAK_SELF();
        [cell setConfirmOrderBlock:^{
            ShowIndicatorInView(weakSelf.view);
            [GetOrderManager() asyncConfirmOrderWithOrderId:orderId confirm:YES completeBlock:^(NSError *error) {
                HideTipsOnView(weakSelf.view);
                
                if (error == nil) {
                    ShowTipsOnView(@"确认成功", weakSelf.view);
                } else {
                    ShowTipsOnView(error.localizedDescription, weakSelf.view);
                }
            }];
        }];
        
        [cell setAssignOrderBlock:^{
            UUOrderAssignVC *assignVC = [UUOrderAssignVC instanceOfAppropriate];
            assignVC.orderId = orderId;
            [weakSelf.navigationController pushViewController:assignVC animated:YES];
        }];
        
        _cell = cell;
    }
    
    if ([self tableView:tableView numberOfRowsInSection:indexPath.section] - 2 == indexPath.row) {
        _cell.showSeparator = NO;
    } else {
        _cell.showSeparator = YES;
    }
    
    return _cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.row == 3) {
        if (indexPath.section == 0) {
            [self switchToOrderStatus:UUOrderStatusWaitingForConfirm];
        } else if (self.ordersForWaitingForAssign.count > 0) {
            [self switchToOrderStatus:UUOrderStatusWaitingForAssign];
        } else {
            [self switchToOrderStatus:UUOrderStatusWaitingForService];
        }
    } else {
        id orderId = [self orderIdForIndexPath:indexPath];
        
        UUOrderDetailVC *detailVC = [UUOrderDetailVC instanceOfAppropriate];
        detailVC.orderId = orderId;
        [self.navigationController pushViewController:detailVC animated:YES];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self.titleView setTitleOffsetWithScrollView:scrollView];
}

#pragma mark - UUOrderManagerObserver methods

- (void)orderManagerDidUpdateOrders:(NSArray<id> *)orders {
    [self updateOrders];
}

#pragma mark - UUUserManagerObserver methods

- (void)userDidUpdate {
    [self.reviewStatusTipsView update];
}

@end
